package com.atguigu.gmall.cart.service;

import com.atguigu.gmall.cart.bean.CartInfo;
import com.atguigu.gmall.cart.mapper.CartInfoMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CartAsyncService {
    @Autowired
    CartInfoMapper cartInfoMapper;
    @Async
    public void saveCartInfo(String userId, CartInfo cartInfo) {
        //给cartInfo初始化创建和更新时间
        cartInfo.setGmtCreate(new Date());
        cartInfo.setGmtModified(new Date());
//        int i = 1/0;
        cartInfoMapper.insert(cartInfo);

    }
    @Async
    public void updateCartInfo(String userId,String skuId,  CartInfo cartInfo) {
        cartInfo.setGmtModified(new Date());
        cartInfoMapper.update(cartInfo,new LambdaUpdateWrapper<CartInfo>()
                .eq(CartInfo::getSkuId,skuId)
                .eq(CartInfo::getUserId , userId));
    }
    @Async
    public void deleteCarts(List<CartInfo> unloginCarts) {
        //userId+skuId 确定唯一的一条数据： 一个用户购买一个商品时只能对应一个购物项
        // （userId,skuId） 复合索引
        unloginCarts.forEach(cartInfo -> {
            cartInfoMapper.delete(new LambdaQueryWrapper<CartInfo>()
                .eq(CartInfo::getUserId , cartInfo.getUserId())
                .eq(CartInfo::getSkuId , cartInfo.getSkuId()));
        });

    }


    public List<CartInfo> queryCartsByUserId(String userId){
        return cartInfoMapper.selectList(new LambdaQueryWrapper<CartInfo>()
            .eq(CartInfo::getUserId , userId));
    }
    @Async
    public void deleteCartInfoByUserIdAndSkuId(String userId, String skuId) {
        cartInfoMapper.delete(new LambdaQueryWrapper<CartInfo>()
            .eq(CartInfo::getUserId , userId)
            .eq(CartInfo::getSkuId , skuId));
    }
}
